import marked from 'marked'
import highLight from 'highlight.js'
import xss from 'xss'
/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:|http:)/.test(path)
}
// 转化 md 语法为 html
export const translateMarkdown = (plainText, isGuardXss = false) => {
  return marked(isGuardXss ? xss(plainText) : plainText, {
    renderer: new marked.Renderer(),
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: true,
    smartLists: true,
    smartypants: true,
    highlight: function(code) {
      /*eslint no-undef: "off"*/
      return highLight.highlightAuto(code).value;
    }
  })
}
// 计算 评论数
export const calcCommentsCount = commentList => {
  let count = commentList.length
  commentList.forEach(item => {
    count += item.replies.length
  })
  return count
}

export function formatDate(date) {
  let today = new Date(date);
  let year = today.getFullYear();
  let month = ("0" + (today.getMonth() + 1)).slice(-2);
  let day = ("0" + today.getDate()).slice(-2);
  let hour = today.getHours();
  let minute = today.getMinutes();
  let second = today.getSeconds();
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

export function showtime(time) {
 let date =
  typeof time === "number"
   ? new Date(time)
   : new Date((time || ""));
 let diff = (new Date().getTime() - date.getTime()) / 1000;
 let dayDiff = Math.floor(diff / 86400);
 
 let isValidDate = Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date.getTime());
 
 if (!isValidDate) {
  console.error("不是有效日期格式");
 }
 
 if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
  return formatDate(date);
 }

 return (
  (dayDiff === 0 &&
   ((diff < 60 && "刚刚") ||
    (diff < 120 && "1分钟前") ||
    (diff < 3600 && Math.floor(diff / 60) + "分钟前") ||
    (diff < 7200 && "1小时前") ||
    (diff < 86400 && Math.floor(diff / 3600) + "小时前"))) ||
  (dayDiff === 1 && "昨天") ||
  (dayDiff < 7 && dayDiff + "天前") ||
  (dayDiff < 31 && Math.ceil(dayDiff / 7) + "周前")
 );
}